<template>
  <el-menu-item v-if="!props.data.children || props.data.children.length == 0" :index="path.resolve(props.data)"
    @click="menuClick(props.data)">
    <el-icon>
      <component :is="resolveIcon(props.data.icon)"></component>
    </el-icon>
    <span>{{ props.data.caption }}</span>
  </el-menu-item>
  <el-sub-menu v-else :index="path.resolve(props.data)">
    <template #title>
      <el-icon>
        <component :is="resolveIcon(props.data.icon)"></component>
      </el-icon>
      <span>{{ props.data.caption }}</span>
    </template>
    <inner-menu v-for="subItem in props.data.children" :data="subItem"></inner-menu>
  </el-sub-menu>
</template>
<script lang="ts" setup name="InnerMenu">
import { MenuItem } from '~/types/ui/MenuItem';
import { menuStore } from '~/store'
import * as ELPIcons from '@element-plus/icons-vue'

const iconKeys: string[] = []
for (const [key] of Object.entries(ELPIcons)) {
  iconKeys.push(key)
}

const props = withDefaults(
  defineProps<{
    data: MenuItem
  }>(), {
  data: null
})

const defaultIcon = 'Crop';
const resolveIcon = (iconName: string) => {
  if (!iconName) return defaultIcon
  if (iconName.indexOf('-') > 0) {
    iconName = iconName.toLowerCase();
    const nameSplits = iconName.split('-');
    iconName = ''
    for (const nameItem of nameSplits) {
      iconName += (nameItem.substring(0, 1).toUpperCase() + nameItem.substring(1));
    }
  }
  if (iconKeys.indexOf(iconName) < 0) return defaultIcon;
  return iconName;
}


const path = {
  resolve(item: MenuItem) {
    return item.path
  }
}

const menuClick = (item: MenuItem) => {
  const state = menuStore()
  state.current = item
}
</script>
